<?php


namespace catchAdmin\project\controller;


use app\common\business\Question;
use app\common\lib\ZhyxMongo;
use app\common\model\BaseModel;
use app\common\model\PatientInfo;
use app\common\model\ProjectSatisfactionAnswer;
use app\common\model\QuestionDetail;
use catchAdmin\permissions\model\Department;
use catcher\base\CatchController;
use catcher\base\CatchRequest;
use catcher\CatchResponse;
use catcher\exceptions\CatchException;
use catcher\exceptions\FailedException;
use catcher\exceptions\MessageException;
use catcher\exceptions\ValidateFailedException;
use catcher\Utils;
use Phinx\Util\Util;
use think\facade\Log;

class Questions extends CatchController
{
    protected $domain = null;

    public function __construct()
    {
        $this->domain = new QuestionDetail();
    }

    public function index(CatchRequest $request): \think\response\Json
    {
        $result = $this->domain->getLists();
        return CatchResponse::success($result);
    }

    public function save(CatchRequest $request): \think\response\Json
    {
        $result = "";
        try {
            $projectId = $request->param("project_id", "", "string");
            if (empty($projectId)) {
                throw new ValidateFailedException("问卷项目id不能为空");
            }
            $projectInfo = (new \app\common\business\Project())->getProjectInfo($projectId);
            $patientId = $request->param("patient_id", "", "string");
            if (empty($patientId)) {
                throw new ValidateFailedException("患者id不能为空");
            }
            $patientInfo = (new PatientInfo())->getPatientInfo($patientId);
            if (empty($patientInfo)) {
                throw new FailedException("患者不存在");
            }

            $result = (new Question())->createQuestion($patientInfo, $projectInfo);

        } catch (MessageException $messageException) {
            Log::error("问卷消息推送失败:" . $messageException->getMessage());
        } catch (FailedException | \Exception $exception) {
            throw new FailedException($exception->getMessage());
        }
        return CatchResponse::success($result);

    }

    public function nodeSatisfactionReport(CatchRequest $request): \think\response\Json
    {

        $createDate = $request->param("date", []);
        if (empty($createDate)) {
            $createDate = [mktime(0, 0, 0, 1, 1, date("Y")), time()];

        } else {
            $createDate[0] = strtotime($createDate[0]);
            $createDate[1] = strtotime($createDate[1]);
        }
        $projectId = $request->param("project_id", "", "string");
        $match = ['created_at' => ['$gte' => $createDate[0], '$lte' => $createDate[1]], 'deleted_at' => 0];
        if (!empty(trim($projectId))) {
            $match['project_id'] = $projectId;
        }
        $collection = ZhyxMongo::getInstance()->setCollection('node');
        $cursor = $collection->aggregate([['$match' => $match], ['$group' => ['_id' => '$node_id', 'send_count' => ['$sum' => '$send_count'], 'answer_count' => ['$sum' => '$answer_count'], 'node_name' => ['$first' => '$node_name']]], ['$project' => ['_id' => false, 'send_count' => true, 'answer_count' => true, 'node_name' => true, 'replay_rate' => ['$multiply' => [['$divide' => [['$toDouble' => '$answer_count'], ['$toDouble' => '$send_count']]], 100]]]]]);
        return CatchResponse::success(iterator_to_array($cursor));

    }

    public function hospitalizationSatisfactionReport(CatchRequest $request): \think\response\Json
    {
        $createDate = $request->param("date", []);
        if (empty($createDate)) {
            $createDate = [mktime(0, 0, 0, 1, 1, date("Y")), time()];

        } else {
            $createDate[0] = strtotime($createDate[0]);
            $createDate[1] = strtotime($createDate[1] . " 23:59:59");
        }
        $projectId = $request->param("project_id", "", "string");
        $match = ['created_at' => ['$gte' => $createDate[0], '$lte' => $createDate[1]], 'deleted_at' => 0, 'questions.classification' => 2];
        if (!empty(trim($projectId))) {
            $match['project_id'] = $projectId;
        }
        $deptId = $request->param("dept_id", "", "string");
        if (!empty(trim($deptId))) {
            $match['patientDeptId'] = (string)$deptId;
        } else {
            #获取部门权限集合
            if (!Utils::isSuperAdmin()) {
                $deptIds = (new BaseModel())->getDeptListByUser([]);
                if (!empty($deptIds)) {
                    foreach ($deptIds as $k => &$v) {
                        $v = (string)$v;
                    }
                    $match["patientDeptId"] = ['$in' => $deptIds];
                }
            }
        }
        $nodeArr = (new ProjectSatisfactionAnswer())->getWholeData([], "label");
        $mydArr = [];
        foreach ($nodeArr as $v) {
            $mydArr[$v["label"]] = 0;
        }

        $collection = ZhyxMongo::getInstance()->setCollection('answer');
        $cursor = $collection->aggregate([['$match' => $match], ['$group' => ['_id' => '$patientDeptId', 'dept_name' => ['$first' => '$patientdeptName'], 'send_count' => ['$sum' => 1], 'replay_count' => ['$sum' => ['$cond' => [['$eq' => ['$status', 2]], 1, 0]]], 'answerList' => ['$push' => '$answer.solution.label']]]]);
        $result = iterator_to_array($cursor);
        if (!empty($result)) {
            foreach ($result as $k => &$v) {
                if (isset($v["answerList"]) && !empty($v["answerList"])) {
                    $v["replay_rate"] = number_format($v["replay_count"] / $v["send_count"] * 100, 2);
                    $v["answer_calc"] = $mydArr;
                    foreach ($v["answerList"] as $ak => $av) {
                        foreach ($av as $value) {
                            if (!isset($v["answer_calc"][$value[0]])) {
                                $v["answer_calc"][$value[0]] = 1;
                            } else {
                                $v["answer_calc"][$value[0]] = (int)$v["answer_calc"][$value[0]] + 1;
                            }
                        }
                    }
                    unset($v["answerList"]);
                }
            }
        }
        return CatchResponse::success($result);
    }


    public function satisfactionFormReport(CatchRequest $request): \think\response\Json
    {
        $createDate = $request->param("date", []);
        if (empty($createDate)) {
            $createDate = [mktime(0, 0, 0, 1, 1, date("Y")), time()];

        } else {
            $createDate[0] = strtotime($createDate[0]);
            $createDate[1] = strtotime($createDate[1] . " 23:59:59");
        }
        $projectId = $request->param("project_id", "", "string");
        $match = ['created_at' => ['$gte' => $createDate[0], '$lte' => $createDate[1]], 'deleted_at' => 0, 'questions.personnelType' => ['$lt' => 3]];
        if (!empty(trim($projectId))) {
            $match['projectId'] = $projectId;
        }
        $deptId = $request->param("dept_id", "", "string");
        if (!empty(trim($deptId))) {
            $match['creator_dept_id'] = (int)$deptId;
        } else {
            #获取部门权限集合
            if (!Utils::isSuperAdmin()) {
                $deptIds = (new BaseModel())->getDeptListByUser([]);
                if (!empty($deptIds)) {

                    $match["creator_dept_id"] = ['$in' => $deptIds];
                }
            }
        }

        $collection = ZhyxMongo::getInstance()->setCollection('answer');
        $cursor = $collection->aggregate([['$match' => $match], ['$group' => ['_id' => 'null', 'send_count' => ['$sum' => 1], 'replay_count' => ['$sum' => ['$cond' => [['$eq' => ['$status', 2]], 1, 0]]]]]]);
        $result = iterator_to_array($cursor);
        $resultData = [];
        if (!empty($result)) {
            $resultData = $result[0];
            if ($resultData["replay_count"] === 0) {
                $resultData["replay_rate"] = 0;
            } else {
                $resultData["replay_rate"] = number_format($resultData["replay_count"] / $resultData["send_count"] * 100, 2);
            }
        }

        return CatchResponse::success($resultData);
    }


}